package com.late13.myapplication;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import org.litepal.LitePal;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import static android.content.Context.INPUT_METHOD_SERVICE;

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.ViewHolder> {

    private static final String TAG = MainActivity.MAIN_TAG + "adapter";

    private List<Task> mTaskList;
    private boolean isFinishedShown = true;
    private int sortBy = Task.SORT_BY_ID;

    static class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox isFinished;
        TextView taskTitle;
        ImageView deleteIcon;
        EditText editText;
        View titlePart;
        TextView taskTime;
        LinearLayout linearLayout;

        public ViewHolder(View view) {
            super(view);
            isFinished = view.findViewById(R.id.task_finished);
            taskTitle = view.findViewById(R.id.task_title);
            deleteIcon = view.findViewById(R.id.task_delete_icon);
            editText = view.findViewById(R.id.task_edit_view);
            titlePart = view.findViewById(R.id.task_title_part);
            taskTime = view.findViewById(R.id.task_time);
            linearLayout = view.findViewById(R.id.task_item_layout);
        }
    }

    public TaskAdapter(List<Task> taskList) {
        mTaskList = taskList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.task_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        Log.v(TAG, "onCreateHolder 1. 设置checkbox点击事件");
        holder.isFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d(TAG, "复选框change触发！");
                final int position = holder.getAdapterPosition();
                final Task task = mTaskList.get(position);
                if(isChecked) {
                    task.setTaskFinished(true);
                    holder.taskTitle.setPaintFlags(holder.taskTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                } else {
                    task.setTaskFinished(false);
                    holder.taskTitle.setPaintFlags(holder.taskTitle.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
                }
                updateFinishedInDB(holder.isFinished, task);
                Log.v(TAG, "准备更新recycler view");
                Log.v(TAG, "准备对adapter中的列表进行排序");
                sortList();
                //Handler handler = new Handler();
                final Runnable r = new Runnable() {
                    public void run() {
                        notifyItemMoved(position, mTaskList.indexOf(task));
                    }
                };
                view.post(r);
                Log.v(TAG, "重新排序过程完成！");
                int diff = 1;
                if(task.getDueDate() != null) {
                    diff = getDayDiff(task.getDueDate().getTime());
                }
                setTitleTimeColor(isChecked, holder, diff);
                if(isChecked && (!isFinishedShown)) {
                    holder.linearLayout.setVisibility(View.GONE);
                }
            }
        });

        Log.v(TAG, "onCreateHolder 2. 设置删除按钮功能");
        holder.deleteIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v(TAG, "弹出对话框确认是否删除");
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setMessage("你确定要删除吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.v(TAG, "menu-delete已点击，准备删除数据库中的项目");
                        int position = holder.getAdapterPosition();
                        Task task = mTaskList.get(position);
                        deleteTaskFromDB(holder.taskTitle, task);
                        deleteItem(task, position);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.v(TAG, "删除已取消");
                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });

        Log.v(TAG, "onCreateHolder 3. 设置task title单击事件");
        holder.titlePart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v(TAG, "task title点击事件触发");
                int position = holder.getAdapterPosition();
                Task task = mTaskList.get(position);

                Intent intent = new Intent(v.getContext(), Editor.class);
                intent.putExtra("id", task.getTaskId());
                ((Activity)v.getContext()).startActivityForResult(intent, 1);
            }
        });

        Log.v(TAG, "onCreateHolder 4. 设置task title长按事件");
        holder.titlePart.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                String title = holder.taskTitle.getText().toString();
                holder.editText.setText(title);
                holder.editText.setSelection(title.length());
                Log.d(TAG, "设置可见");
                holder.taskTitle.setVisibility(View.GONE);
                holder.editText.setVisibility(View.VISIBLE);
                Log.d(TAG, "获取焦点");
                holder.editText.requestFocus();
                InputMethodManager imm = (InputMethodManager)holder.editText.getContext().getSystemService(INPUT_METHOD_SERVICE);
                imm.showSoftInput(holder.editText, InputMethodManager.SHOW_IMPLICIT);
                return true;
            }
        });

        Log.v(TAG, "onCreateHolder 5. 设置edit text焦点变更事件");
        holder.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus) {
                    String title = holder.editText.getText().toString();
                    if("".equals(title.trim())) {
                        Toast.makeText(v.getContext(), "标题不能为空，恢复为原标题", Toast.LENGTH_SHORT).show();
                        holder.editText.setText(holder.taskTitle.getText());
                    } else {
                        Log.d(TAG, "保存title到Task中");
                        int position = holder.getAdapterPosition();
                        Task task = mTaskList.get(position);
                        task.setTaskTitle(title);
                        updateTitleInDB(holder.taskTitle, task);
                        holder.taskTitle.setText(task.getTaskTitle());
                    }
                    Log.d(TAG, "设置textView为可见，editText不可见");
                    holder.editText.setVisibility(View.GONE);
                    holder.taskTitle.setVisibility(View.VISIBLE);
                }
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Task task = mTaskList.get(position);
        holder.isFinished.setChecked(task.isTaskFinished());
        holder.taskTitle.setText(task.getTaskTitle());

        Date dueDate = task.getDueDate();
        int diff = 1;
        if(dueDate == null) {
            holder.taskTime.setText(Task.DATE_DEFAULT_STRING);
        } else {
            diff = getDayDiff(dueDate.getTime());
            Log.v(TAG, "dueDate = " + Task.DATE_FORMAT.format(dueDate) + ", diff = " + diff);
            if (diff < 0) {
                holder.taskTime.setText(Task.DATE_FORMAT.format(dueDate));
            } else{
                if (diff < 7) {
                    holder.taskTime.setText(diff + "天后");
                } else {
                    holder.taskTime.setText(Task.DATE_FORMAT.format(dueDate));
                }
            }
        }
        setTitleTimeColor(task.isTaskFinished(), holder, diff);

        if((!isFinishedShown) && task.isTaskFinished()) {
            holder.linearLayout.setVisibility(View.GONE);
        } else {
            holder.linearLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     *
     * @param dueDateTime
     * @return 指定时间距现在几天，未来时间为正数，过去时为负数
     */
    public int getDayDiff(long dueDateTime) {
        return (int) (dueDateTime/1000/60/60/24 - System.currentTimeMillis()/1000/60/60/24);
    }

    public void setTitleTimeColor(boolean isTaskFinished, ViewHolder holder, long diff) {
        if(!isTaskFinished && diff < 0) {
            holder.taskTitle.setTextColor(Color.RED);
            holder.taskTime.setTextColor(Color.RED);
        } else {
            holder.taskTitle.setTextColor(R.attr.itemTextColor);
            holder.taskTime.setTextColor(holder.taskTime.getResources().getColor(R.color.dueDateText));
        }
    }

    @Override
    public int getItemCount() {
        return mTaskList.size();
    }

    public void setSortBy(int sort_by) {
        this.sortBy = sort_by;
    }
    /**
     * 排序，读取private变量sort_by, private变量mTaskList
     */
    public void sortList(){
        Log.v(TAG, "sortBy = " + sortBy);
        if(sortBy == Task.SORT_BY_ID) {
            Collections.sort(mTaskList, new Comparator<Task>() {
                @Override
                public int compare(Task o1, Task o2) {
                    int firstFinish = o1.isTaskFinished()?1:0;
                    int secondFinish = o2.isTaskFinished()?1:0;
                    int i = firstFinish - secondFinish;
                    if(0 == i) {
                        return (o2.getTaskId() - o1.getTaskId());
                    }
                    return i;
                }
            });
        } else if (sortBy == Task.SORT_BY_DATE) {
            Collections.sort(mTaskList, new Comparator<Task>() {
                @Override
                public int compare(Task o1, Task o2) {
                    int firstFinish = o1.isTaskFinished()?1:0;
                    int secondFinish = o2.isTaskFinished()?1:0;
                    int i = (firstFinish - secondFinish);
                    if(0 == i) {
                        long date1;
                        long date2;
                        if (o1.getDueDate() != null) {
                            date1 = o1.getDueDate().getTime();
                        } else {
                            date1 = Long.MAX_VALUE;
                        }
                        if (o2.getDueDate() != null) {
                            date2 = o2.getDueDate().getTime();
                        } else {
                            date2 = Long.MAX_VALUE;
                        }
                        if(date2 > date1) {
                            return -1;
                        } else if (date2 < date1) {
                            return 1;
                        } else {
                            return (o2.getTaskId() - o1.getTaskId());
                        }
                    }
                    return i;
                }
            });
        }
    }

    public void setFinishedShown(boolean isFinishedShown) {
        this.isFinishedShown = isFinishedShown;
    }

    public void showFinish(boolean isShown) {
        isFinishedShown = isShown;
        notifyDataSetChanged();
    }

    public void addItem(Task task) {
        Log.v(TAG, "准备向recycler view中新增项目");
        mTaskList.add(task);
        sortList();
        notifyDataSetChanged();
    }

    public void deleteItem(Task task, int position) {
        mTaskList.remove(task);
        notifyItemRemoved(position);
    }

    public void deleteTaskFromDB(View v, Task task) {
        if(task.getTaskId() != -1) {
            LitePal.delete(TaskInDB.class, task.getTaskId());
        }
    }

    public void updateTitleInDB(View v, Task task) {
        TaskInDB taskInDB = new TaskInDB();
        taskInDB.setTitle(task.getTaskTitle());
        taskInDB.update(task.getTaskId());
    }

    public void updateFinishedInDB(View v, Task task) {
        TaskInDB taskInDB = new TaskInDB();
        if(task.isTaskFinished()) {
            taskInDB.setFinished(true);
        } else {
            taskInDB.setToDefault("finished");
        }
        taskInDB.update(task.getTaskId());
    }
}
